/*
 * Licensed under the License, Version 1.0 (the "License");
 * You may obtain a copy of the License at
 *   http://www.heavenick.com/license/License 
 * Copyright information Heavenick to all.
 * Unless the applicable legal requirements or written 
 * consent, can use or around the code, and no warranties 
 * of any kind and state responsibility.
 */
package com.heavenick.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.junit.Before;
import org.junit.Test;

/**
 * 
 * @author Heavenick
 * @version 1.0
 * @date 2012-9-4 下午7:14:18
 */
public class ThreadTest {

	private Vector<String> vector = null;

	private StringBuffer buffer = null;

	private int threadCount = 50;

	private int count = 0;

	@Before
	public void initdata() {
		vector = new Vector<String>();
		for (int i = 0; i < 10000; i++) {
			vector.add("testString" + i);
		}
		buffer = new StringBuffer();
	}

	@Test
	public void initThread() {
		LocalSubThread localsubthread = new LocalSubThread();
		for (int i = 0; i < threadCount; i++) {
			if (vector.size() > 0) {
				Thread thread = new Thread(new ThreadJob(this));
				localsubthread.register(thread);
				thread.start();
			}
		}
		localsubthread.waitThreadDead();
		System.out.println(buffer.toString());
		System.out.println("count : " + count);
	}

	public Vector<String> getVector() {
		return vector;
	}

	public boolean jobProcess(String str) {
		++count;
		str = str.toLowerCase().substring(10);
		buffer.append(str + ",");
		return true;
	}

}

class ThreadJob implements Runnable {
	private ThreadTest impl = null;

	public ThreadJob(ThreadTest impl) {
		this.impl = impl;
	}

	public void run() {
		while (impl.getVector().size() > 0) {
			String str = null;
			try {
				str = impl.getVector().remove(0);
			} catch (ArrayIndexOutOfBoundsException e1) {
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
			impl.jobProcess(str);
		}
	}
}

class LocalSubThread {
	private List<Thread> threadlist = new ArrayList<Thread>();

	public void register(Thread thread) {
		threadlist.add(thread);
	}

	public void cancel(Thread thread) {
		remove(thread);
		if (thread.isAlive())
			thread.interrupt();
	}

	private void remove(Thread thread) {
		threadlist.remove(thread);
	}

	public int getSubAliveCount() {
		return threadlist.size();
	}

	public void waitThreadDead() {
		while (threadlist.size() > 0) {
			for (int i = 0; i < threadlist.size();) {
				Thread thread = threadlist.get(i);
				if (thread.isAlive()) {
					i++;
				} else {
					remove(thread);
				}
			}
		}
	}
}